package com.nulstudio.sppm.controller;

import com.nulstudio.sppm.network.*;
import com.nulstudio.sppm.entity.Supplier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

@Controller
@CrossOrigin(origins = "*")
@RequestMapping("/service/supplier")
public final class SupplierController {

    private final List<Supplier> supplierList = new ArrayList<>();

    @RequestMapping("/fetchAll")
    @ResponseBody
    public Result<Supplier[]> fetchAll(@RequestBody Request<?> request) {
        final Supplier[] suppliers = new Supplier[supplierList.size()];
        for (int i = 0; i < supplierList.size(); ++i) {
            suppliers[i] = supplierList.get(i);
        }
        return new Result<>(suppliers);
    }

    @RequestMapping("/createEntry")
    @ResponseBody
    public Result<CreateSupplierResponse> createEntry(@RequestBody Request<CreateSupplierRequest> rawRequest) {
        final CreateSupplierRequest request = rawRequest.getRequest();
        if (supplierList.stream().filter(supplier -> supplier.getName().equals(request.getName()))
                .findFirst().orElse(null) != null) {
            return new Result<>(100, "Fuck");
        }
        final int id = supplierList.isEmpty() ? 1 : supplierList.get(supplierList.size() - 1).getId() + 1;
        final Supplier supplier = new Supplier(id, request.getName(), request.getContact(),
                request.getPhone(), request.getEmail(), request.getAddress());
        supplierList.add(supplier);
        return new Result<>(new CreateSupplierResponse(id));
    }

    @RequestMapping("/modifyEntry")
    @ResponseBody
    public Result<?> modifyEntry(@RequestBody Request<Supplier> request) {
        final Supplier supplier = supplierList.stream()
                .filter(item -> item.getId() == request.getRequest().getId())
                .findFirst().orElse(null);
        if (supplier == null) {
            return new Result<>(100, "Fuck");
        }
        supplierList.remove(supplier);
        supplierList.add(request.getRequest());
        supplierList.sort(Comparator.comparing(Supplier::getId));
        return new Result<>();
    }

    @RequestMapping("/deleteEntry")
    @ResponseBody
    public Result<?> deleteEntry(@RequestBody Request<DeleteSupplierRequest> request) {
        final Set<Integer> deleteIds = new HashSet<>(Arrays.asList(request.getRequest().getId()));
        final List<Supplier> suppliers = supplierList.stream()
                .filter(item -> !deleteIds.contains(item.getId()))
                .collect(Collectors.toList());
        supplierList.clear();
        supplierList.addAll(suppliers);
        return new Result<>();
    }
}
